<!--
 * 组织/部门 列表
 *
 * @author tqfeiyang
 * @since 2024-09-19
-->
<template>
    <a-form class="smart-query-form" v-privilege="'oa:notice:query'">
        <a-row class="smart-query-form-row">
          <a-form-item label="关键字" class="smart-query-form-item">
            <a-input style="width: 300px" v-model:value="keywords" placeholder="请输入关键字" />
          </a-form-item>
          <a-form-item class="smart-query-form-item smart-margin-left10">
              <a-space>
                  <a-button type="primary" @click="onSearch">
                      <template #icon>
                          <SearchOutlined />
                      </template>
                      查询
                  </a-button>
                  <a-button @click="resetQuery">
                      <template #icon>
                          <ReloadOutlined />
                      </template>
                      重置
                  </a-button>
              </a-space>
          </a-form-item>
        </a-row>
    </a-form>

    <a-card size="small" :bordered="false">
        <a-row class="smart-table-btn-block">
            <div class="smart-table-operate-block">
                <a-button type="primary" @click="addDepartment">
                    <template #icon>
                        <PlusOutlined />
                    </template>
                    新建
                </a-button>
            </div>
            <div class="smart-table-setting-block">
                <TableOperator v-model="tableColumns" :refresh="getDepartmentTree" />
            </div>
        </a-row>

        <a-table
            rowKey="departmentId"
            :columns="tableColumns"
            :data-source="departmentTree"
            :defaultExpandAllRows="false"
            :defaultExpandedRowKeys="defaultExpandedRowList"
            :loading="tableLoading"
            :pagination="false"
            size="small"
            bordered
        >
            <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'action'">
                    <div class="smart-table-operate">
                        <a-button type="link" @click="addDepartment(record)">添加下级</a-button>
                        <a-button type="link" @click="updateDepartment(record)">编辑</a-button>
                        <a-button type="link" v-if="record.departmentId !== topDepartmentId" @click="deleteDepartment(record)" danger>删除</a-button>
                    </div>
                </template>
            </template>
        </a-table>
    </a-card>

  <DepartmentModal ref="departmentModel" @refresh="getDepartmentTree" />
</template>

<script setup>
  import { reactive, ref, computed, onMounted, createVNode } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import _ from 'lodash';
  import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
  import TableOperator from '/@/components/support/table-operator/index.vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import DepartmentModal from './components/department-modal.vue';
  import { departmentApi } from '/@/api/business/organization/department-api';

  // -------------------- 查询 --------------------

  const DEPARTMENT_PARENT_ID = 0;

  const tableLoading = ref(false);

  // 搜索关键字
  const keywords = ref('');
  
  // 所有部门列表
  const departmentList = ref([]);

  // 部门树形数据
  const departmentTree = ref([]);

  // 存放部门id和部门，用于查找
  const idInfoMap = ref(new Map());

  // 默认展开的行
  const defaultExpandedRowList = reactive([]);

  // 顶层的部门id
  const topDepartmentId = ref();

  const tableColumns = ref([
    {
      title: '名称',
      dataIndex: 'name',
      sorter: (a, b) => {},
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '排序',
      dataIndex: 'sort',
      sorter: (a, b) => {},
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '备注',
      dataIndex: 'remark',
      sorter: (a, b) => {},
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: (a, b) => {},
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      sorter: (a, b) => {},
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
    },
  ]);

  const queryFormState = {
    pageNum: 1,
    pageSize: PAGE_SIZE,
    orderBy: null,
    direction: null,
    keywords: undefined, //关键字
    parentId: undefined, //上级id
    name: undefined, //名称
    remark: undefined, //备注
  };

  const queryForm = reactive({ ...queryFormState });

  onMounted(() => {
    getDepartmentTree();
  });

  async function getDepartmentTree() {
    try {
      tableLoading.value = true;
      const result = await departmentApi.getAllDepartmentList()
      departmentList.value = result.data;
      console.log("departmentList", departmentList)

      departmentList.value.forEach((e) => {
        idInfoMap.value.set(e.departmentId, e);
      });
      console.log('idInfoMap', idInfoMap)
      
      departmentTree.value = buildDepartmentTree(departmentList.value, DEPARTMENT_PARENT_ID);
      console.log('departmentTree', departmentTree)

      if (!_.isEmpty(departmentTree.value) && departmentTree.value.length > 0) {
        topDepartmentId.value = departmentTree.value[0].departmentId;
      }
      console.log('topDepartmentId', topDepartmentId)

      defaultExpandedRowList.value = [];
      defaultExpandedRowList.push(topDepartmentId.value);
      console.log('defaultExpandedRowList', defaultExpandedRowList)

    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      tableLoading.value = false;
    }
  }
  
  function onSearch() {
    if (!keywords.value) {
      departmentTree.value = buildDepartmentTree(departmentList.value, DEPARTMENT_PARENT_ID);
      return;
    }

    let originData = departmentList.value.concat();
    if (!originData) {
      return;
    }

    let filterDepartment = originData.filter((e) => e.name.indexOf(keywords.value) > -1);
    let filterDepartmentList = [];
    filterDepartment.forEach((e) => {
      recursionFilterDepartment(filterDepartmentList, e.departmentId, false);
    });
    departmentTree.value = buildDepartmentTree(filterDepartmentList, DEPARTMENT_PARENT_ID);
  }

  function buildDepartmentTree(data, parentId) {
    let children = data.filter((e) => e.parentId === parentId) || [];
    if (!_.isEmpty(children)) {
      children.forEach((e) => {
        e.children = buildDepartmentTree(data, e.departmentId);
      });
      return children;
    }
    return null;
  }

  function recursionFilterDepartment(resList, id, unshift) {
    let info = idInfoMap.value.get(id);
    if (!info || resList.some((e) => e.departmentId === id)) {
      return;
    }
    if (unshift) {
      resList.unshift(info);
    } else {
      resList.push(info);
    }
    if (info.parentId && info.parentId !== 0) {
      recursionFilterDepartment(resList, info.parentId, unshift);
    }
  }

  function resetQuery() {
    keywords.value = '';
    onSearch();
  }

  // ----------------- 新建/编辑 ------------------

  const departmentModel = ref();

  function addDepartment(record) {
    console.log('addDepartment', record)
    departmentModel.value.showModal({
        departmentId: 0,
        name: '',
        parentId: record.departmentId ?? null,
      });
  }

  function updateDepartment(record) {
    departmentModel.value.showModal(record);
  }

  function deleteDepartment(record) {
    Modal.confirm({
      title: '确定要删除如下数据吗?',
      icon: createVNode(ExclamationCircleOutlined),
      content: record.name,
      okText: '删除',
      okType: 'danger',
      async onOk() {
        try {
          SmartLoading.show();
          await departmentApi.deleteDepartment(record.departmentId);
          message.success('删除成功!');
          getDepartmentTree();
        } catch (e) {
          smartSentry.captureError(e);
        } finally {
          SmartLoading.hide();
        }
      },
      cancelText: '取消',
      onCancel() {},
    });
  }
</script>

<style lang="less" scoped>
</style>
